package com.sf.dlb.web.controller;


import com.sf.dlb.bean.AppVersionBean;
import com.sf.dlb.constant.ResponseConstant;
import com.sf.dlb.constant.SystemConstant;
import com.sf.dlb.utils.GsonUtils;
import com.sf.dlb.utils.ResultVOUtil;
import com.sf.dlb.vo.ResultVO;
import com.sf.dlb.web.config.Global;
import com.sf.dlb.web.service.AppVersionService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;


/**
 * APP版本相关
 * Created by jing.tan on 2018/12/10.
 */
@RestController
@RequestMapping(value = "/v1/version")
public class AppVersionController {
    private static Logger logger = LoggerFactory.getLogger(AppVersionController.class);
    @Resource
    private Global global;
    @Autowired
    private AppVersionService appVersionService;
    /**
     * 获取APP版本列表
     *
     * @return
     */
    @GetMapping(value = {"/list/{systemType}","/list"})
    @ResponseBody
    public Object list(HttpServletRequest request,@PathVariable(required = false) String systemType) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        resultVO=appVersionService.findByList(systemType);
        logger.info("list response json " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 更新版本信息
     */
    @PostMapping(value = "/updateAppVersion")
    @ResponseBody
    public Object updateAppVersion(HttpServletRequest request, AppVersionBean appVersionBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        logger.info("updateAppVersion request json === " + GsonUtils.getInstance().toJson(appVersionBean));
        if(appVersionBean.getId()==null){
            return ResultVOUtil.error(ResponseConstant.ERROR, "缺少版本id");
        }
        //获取上传的文件
        if(null!=appVersionBean.getFile()&&!appVersionBean.getFile().isEmpty()) {
            try {
                String absolutePath = global.file_image_absolute_path + SystemConstant.APP_VERSION_FILE_PATH;
                String relativePath=global.file_image_relative_path+SystemConstant.APP_VERSION_FILE_PATH;
                MultipartFile multipartFile = appVersionBean.getFile();
                String originalFilename = multipartFile.getOriginalFilename();
                if(originalFilename.lastIndexOf(".")<0){
                    return ResultVOUtil.error(ResponseConstant.ERROR, "上传文件格式错误");
                }
                String originalFilenamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                String originalFilenameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String multipartFileName = originalFilenamePrefix + appVersionBean.getVersionName() + originalFilenameSuffix;
                String localFileName = absolutePath + "/" + multipartFileName;
                String relativeFileName = new StringBuffer().append(relativePath).append("/").append(multipartFileName).toString();
                File localFile = new File(localFileName);
                multipartFile.transferTo(localFile);
                appVersionBean.setDownloadUrl(relativeFileName);
                logger.info("updateAppVersion localFileName={},relativeFileName={}", localFileName, relativeFileName);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultVOUtil.error(ResponseConstant.ERROR, "updateAppVersion 上传文件失败");

            }
        }
        resultVO=appVersionService.updateAppVersion(appVersionBean);
        logger.info("updateAppVersion response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 删除版本信息
     */
    @DeleteMapping(value = "/deleteAppVersion/{id}")
    @ResponseBody
    public Object deleteAppVersion(HttpServletRequest request, @PathVariable("id") Long id) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        if(id==null){
            return ResultVOUtil.error(ResponseConstant.ERROR, "缺少版本id");
        }
        logger.info("deleteAppVersion request json === " + id);
        resultVO=appVersionService.deleteAppVersion(id);
        logger.info("deleteAppVersion response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
    /**
     * 增加版本信息
     */
    @PostMapping(value = "/addAppVersion")
    @ResponseBody
    public Object addAppVersion(HttpServletRequest request,AppVersionBean appVersionBean) {
        ResultVO resultVO=(ResultVO)request.getAttribute("token");
        logger.info("addAppVersion request json === " + GsonUtils.getInstance().toJson(appVersionBean));
        if(null==appVersionBean.getVersionNumber()){
            return ResultVOUtil.error(ResponseConstant.ERROR, "版本号不能为空");
        }
        if(StringUtils.isEmpty(appVersionBean.getVersionName())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "版本名称不能为空");
        }
        if(StringUtils.isEmpty(appVersionBean.getSystemType())){
            return ResultVOUtil.error(ResponseConstant.ERROR, "系统类型不能为空");
        }
        //如果是安卓，必须上传安装包
        if(appVersionBean.getSystemType().equals("1")){
            if(null==appVersionBean.getFile()||appVersionBean.getFile().isEmpty()){
                return ResultVOUtil.error(ResponseConstant.ERROR, "安装文件不能为空");
            }
        //如果是IOS，只需要传链接就可以了
        }else if(appVersionBean.getSystemType().equals("2")){
            if(StringUtils.isEmpty(appVersionBean.getDownloadUrl())){
                return ResultVOUtil.error(ResponseConstant.ERROR, "下载链接不能为空");
            }
        }
        //获取上传的文件
        if(null!=appVersionBean.getFile()&&!appVersionBean.getFile().isEmpty()) {
            try {
                String absolutePath = global.file_image_absolute_path + SystemConstant.APP_VERSION_FILE_PATH;
                String relativePath = global.file_image_relative_path + SystemConstant.APP_VERSION_FILE_PATH;
                MultipartFile multipartFile = appVersionBean.getFile();
                String originalFilename = multipartFile.getOriginalFilename();
                if (originalFilename.lastIndexOf(".") < 0) {
                    return ResultVOUtil.error(ResponseConstant.ERROR, "上传文件格式错误");
                }
                String originalFilenamePrefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
                String originalFilenameSuffix = originalFilename.substring(originalFilename.lastIndexOf("."));
                String multipartFileName = originalFilenamePrefix + appVersionBean.getVersionName() + originalFilenameSuffix;
                String localFileName = absolutePath + "/" + multipartFileName;
                String relativeFileName = new StringBuffer().append(relativePath).append("/").append(multipartFileName).toString();
                File localFile = new File(localFileName);
                multipartFile.transferTo(localFile);
                appVersionBean.setDownloadUrl(relativeFileName);
                logger.info("addAppVersion localFileName={},relativeFileName={}", localFileName, relativeFileName);
            } catch (Exception e) {
                e.printStackTrace();
                return ResultVOUtil.error(ResponseConstant.ERROR, "addAppVersion 上传文件失败");
            }
        }
        resultVO=appVersionService.addAppVersion(appVersionBean);
        logger.info("addAppVersion response json === " + GsonUtils.getInstance().toJson(resultVO));
        return resultVO;
    }
}
